package cn.itcast.n8;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static cn.itcast.n2.util.Sleeper.sleep;

/**
 * @author: AirMan
 * @date: 2025/4/25 14:34
 * @description:
 */
@Slf4j(topic = "c.TestCyclicBarrier_my")
public class TestCyclicBarrier_my {
    public static void main(String[] args) {

        ExecutorService pool = Executors.newFixedThreadPool(2);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () -> {log.debug("finished ! ! !");});

        pool.execute(() -> {
            log.debug("start...");
            sleep(1);
            try {
                cyclicBarrier.await();
                log.debug("finished...");
            } catch (InterruptedException | BrokenBarrierException e) {
                throw new RuntimeException(e);
            }
        });

        pool.execute(() -> {
            log.debug("start...");
            sleep(1);
            try {
                sleep(2);
                cyclicBarrier.await();
                log.debug("finished...");
            } catch (InterruptedException | BrokenBarrierException e) {
                throw new RuntimeException(e);
            }
        });

        pool.shutdown();

    }
}
